<template>
  <div class="yy-page yy-queue-category">
    <div class="yy-page-header">
      <div class="yy-page-header_title">科目管理</div>
      <div class="yy-page-header_action">
        <el-form-item label="科目名称" prop="itemName" style="margin: 1.2rem">
          <el-input
              v-model="table.itemName"
              placeholder="请输入科目名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button @click="getCategoryList()">刷新</el-button>
        <el-button type="primary" @click="onOpenImportModal">导入科目</el-button>
        <el-button @click="onDownloadTemplate">下载模板</el-button>
        <el-button color="#009688" @click="onOpenDialog()">新增科目</el-button>
      </div>
    </div>
    <div class="yy-page-data">
      <WidgetTable  :is-loading="table.isLoading" :columns="table.columns" :data="table.data" :formats="table.formats" :paging-data="table.paging"></WidgetTable>
    </div>
    <WidgetFormDialog ref="widgetFormDialogRef"
                      :form-fields="dialog.formFields"
                      :model-instance="dialog.modelInstance"
                      :save-api-fun="dialog.saveApiFun"
                      :update-api-fun="dialog.updateApiFun"
                      :option="{
                      businessName: '科目',
                      formLabelWidth: '100px'
                    }"
                      @edit-callback="onEditCallback"
    />
    <ImportModal ref="importModalRef"></ImportModal>
  </div>
</template>

<script setup lang="ts">

import {onBeforeMount, reactive, ref} from "vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {formatDate} from "@/utils/yayi";
import {QueueRegItemModel} from "@/model/QueueRegItemModel";
import RegItemApi from "@/api/queue/RegItemApi";
import {listDept} from "@/api/system/dept";
import EmployeeApi from "@/api/system/empl";
import RegCategoryApi from "@/api/queue/RegCategoryApi";
import {useRouter} from "vue-router";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import WidgetFormDialog from "@/components/widget/WidgetFormDialog.vue";
import ImportModal from "@/views/queue/reg_item/ImportModal.vue";


const router = useRouter()

const dialog = reactive<{formFields: WidgetFormField[],modelInstance: BaseModel, saveApiFun: any, updateApiFun: any}>({
  modelInstance: new QueueRegItemModel(),
  saveApiFun: RegItemApi.saveRegItem,
  updateApiFun: RegItemApi.updateRegItem,
  formFields: [
    { field: 'deptId', label: '科室', type: 'select',
      placeholder: '请选择科室',
      required: [{required: true, message: '科室不能为空', trigger: 'blur'}],
      options: []
    },
    {field: 'name', label: '名称', type: 'text', placeholder: '请输入科目名称', required: [{required: true, message: '名称不能为空', trigger: 'blur'}]},
    {field: 'code', label: '代码', type: 'text', placeholder: '请输入科目代码', required: [{required: true, message: '代码不能为空', trigger: 'blur'}]},

    {field: 'state', label: '状态', type: 'radioGroup', initVal: 1, options: [{label: '启用', value: 1}, {label: '停用', value: 0}]}
  ]
})

const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: QueueRegItemModel[],
  itemName: any,
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "fixed": 'left',
      "align": 'center',
      "width": 60
    },
    {
      "field":"name",
      "label":"名称",
      "showable":true,
      "fixed": 'left'
    },
    {
      "field":"code",
      "label":"代码",
      "showable":true
    },
    {
      "field":"deptCode",
      "label":"科室代码",
      "showable":true
    },
    {
      "field":"deptName",
      "label":"科室名称",
      "showable":true
    },
    {
      "field":"scheduleType",
      "label":"排班方式",
      "showable":true
    },
    {
      "field":"keywords",
      "label":"检索码",
      "showable":true,
    },
    {
      "field":"updateName",
      "label":"更新用户",
      "showable":true,
      "width": 120
    },
    {
      "field":"updateTime",
      "label":"更新时间",
      "showable":true,
      "width": 160
    },
    {
      "field":"state",
      "label":"状态",
      "showable":true,
      "sortable":false,
      "fixed": 'right',
      "align": 'center',
      "width": 60,
    },
    {
      "field":"action",
      "label":"操作",
      "width": 210,
      "showable":true,
      "sortable":false,
      "align": 'center',
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: true,
    pageSize: 50,
    pageIndex: 1,
    total: 0,
    pageChange: (pageIndex: number) => {
      onPageChange(pageIndex)
    }
  },
  data: [],
  itemName: null,
  formats: {
    'state': {
      textType:'text',
      typeFormat: QueueRegItemModel.getStateType,
      labelFormat: QueueRegItemModel.getStateLabel
    },
    'updateTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'scheduleType': {
      labelFormat: (val, row) => {
        return QueueRegItemModel.getSchedultType(val)?.label
      }
    },
    'action': {
      items: [
        {label: '编辑', elType: 'button', value: 'edit', atClick: (data: QueueRegItemModel) => onOpenDialog(data)},
        {label: '成员', elType: 'button', type:'success', value: 'member',
          atClick: (data: QueueRegItemModel) => router.push({name: 'QueueRegItemMember', query: {itemId: data.id, itemName: data.name, deptId: data.deptId}})},
        {label: '删除', elType: 'button', value: 'delete', confirm: {title: '您确定要删除该科目吗？', atConfirm: (data: QueueRegItemModel) => onDeleteCategory(data)}}
      ]
    }
  }
})

const widgetFormDialogRef = ref()
const employeeItemManageDialogRef = ref()
const importModalRef = ref()

onBeforeMount(() => {
  getCategoryList(table.paging.pageIndex)
  onSearchRemoteDepart()
})

const getCategoryList = (pageIndex = 1) => {
  table.isLoading = true
  RegItemApi.listRegItem(pageIndex, table.paging.pageSize, table.itemName).then((pagingData) => {
    table.data = pagingData.data
    table.paging = Object.assign({}, table.paging, {
      pageIndex: pagingData.pageIndex,
      total: pagingData.total
    })
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onOpenDialog = (category?: QueueRegItemModel) => {
  if (category) {
    const departFormField = dialog.formFields.find(item => item.field === 'deptId')
    departFormField.options = [{
      value: category.deptId,
      label: category.deptName
    }]
  }
  widgetFormDialogRef.value.onShowDialog(category)
}

const onSetEmployeeItem = () => {
  employeeItemManageDialogRef.value.onShowDialog()
}

const onDeleteCategory = (category: QueueRegItemModel) => {
  RegItemApi.deleteRegItem(category.id).then(() => {
    const index = table.data.findIndex(item => item.id === category.id);
    if (index >= 0){
      table.data.splice(index, 1)
    }
  })
}

const onSearchRemoteDepart = () => {
  listDept(null).then(res => {
    const formField = dialog.formFields.find(item => item.field === 'deptId')
    formField.options = res.data.map(item => Object.assign({label: item.deptName, value: item.deptId.toString()}))
    console.log("dept options",formField.options)
  })
}

const onSearchRemoteCategory = (searchKey: string) => {
  RegCategoryApi.listRegCategory().then(res => {
    const formField = dialog.formFields.find(item => item.field === 'categoryId')
    formField.options = res.map(item => Object.assign({label: item.name, value: item.id}))
  })
}

const onSearchRemoteEmployee = (searchKey: string = null) => {
  const property = widgetFormDialogRef.value.getFormFieldValue()
  EmployeeApi.listEmployee(searchKey,property['deptId'] || null, 1, 50).then(res => {
    const formField = dialog.formFields.find(item => item.field === 'emplId')
    formField.options = res.data.map(item => Object.assign({label: item.name + `(${item.levelName})`, value: item.id}))
  })
}

const onOpenImportModal = () => {
  importModalRef.value.onShowModel()
}

const onDownloadTemplate = () => {
  RegItemApi.downloadTemplate()
}

const onPageChange = (pageIndex: number) => {
  if (pageIndex != table.paging.pageIndex) {
    getCategoryList(pageIndex);
  }
}

const onEditCallback = (category: QueueRegItemModel) => {
  if (!category.emplId) {
    category.emplName = ''
  }
  const index = table.data.findIndex(item => item.id === category.id);
  if (index < 0) {
    table.data.unshift(category)
    table.paging = Object.assign({}, table.paging, {
      total: table.paging.total + 1
    })
  } else {
    table.data.splice(index, 1, category)
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  getCategoryList();
}
</script>
<style scoped lang="scss">
.yy-queue-category {}
</style>
